package com.xdtech.sys.aspect;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.xdtech.common.utils.JsonUtil;
import com.xdtech.common.utils.RequestUtil;
import com.xdtech.sys.model.Log;
import com.xdtech.sys.model.User;
import com.xdtech.sys.service.LogService;
import com.xdtech.sys.util.SessionContextUtil;
import com.xdtech.sys.vo.UserItem;
import com.xdtech.web.model.ResultMessage;

/**
 * 日志记录，添加、删除、修改方法AOP
 * 
 * @author HotStrong
 * 
 */
@Aspect
@Component
public class LogAspect {

	@Autowired
	private LogService logService;// 日志记录Service
	// 本地异常日志记录对象
	private static final Logger logger = LoggerFactory
			.getLogger(LogAspect.class);

	// Service层切点
	@Pointcut("@annotation(com.xdtech.sys.aspect.SystemServiceLog)")
	public void serviceAspect() {

	}

	// Controller层切点
	@Pointcut("@annotation(com.xdtech.sys.aspect.SystemControllerLog)")
	public void controllerAspect() {

	}


	// http://itindex.net/detail/50710-springaop-controller-service
	/**
	 * 前置通知 用于拦截Controller层记录用户的操作
	 * 
	 * @param joinPoint
	 *            切点
	 */
	@Around("controllerAspect()")
	public Object processLog(ProceedingJoinPoint joinPoint)
			throws java.lang.Throwable {
//		System.out.println("执行前" + className + "--------" + methodName);
		// 执行目标方法，并保存目标方法执行后的返回值
		Object rvt = joinPoint.proceed();
//		System.out.println("执行后" + className + "--------" + methodName);
		Class<?> cl = joinPoint.getTarget().getClass();
		String className = cl.getName();
		String methodName = joinPoint.getSignature().getName();
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest();
//		System.out.println(request.getRemoteAddr());
		// 读取session中的用户
		UserItem currentUser = SessionContextUtil.getCurrentUser();
		Log log = new Log();
		try {
			Map params = new HashMap();
			//request里的map不允许修改
			Map pMap = request.getParameterMap();
			for (Object key : pMap.keySet()) {
				if (key.equals("password")) {
					params.put("password", "******");
				}else {
					params.put(key, pMap.get(key));
				}
			}
			
			//记得移除password 密码不让查看
			log.setOperateComment(JsonUtil.getJsonStr(params));
			log.setMethod(className + "." + methodName + "()");
			//日志描述
			String desc = getControllerMethodDescription(joinPoint);
			log.setOperateAction(desc);
			log.setIp(RequestUtil.getClientIp(request));
			if (currentUser == null) {
				log.setOperator(request.getRemoteUser());
			} else {
				log.setOperator(currentUser.getLoginName());
			}
//			log.setOperateComment(log.getOperator()+"-"+desc);
			log.setOperateTime(new Date());
			//判断controller返回结果
			if (rvt instanceof ResultMessage) {
				ResultMessage rm = (ResultMessage) rvt;
				//2 成功 1失败 0 异常
				log.setOperateResult(rm.isSuccess()?"2":"1");
//				log.setOperateComment(rm.getMsg());
			}else if (rvt instanceof ModelAndView) {
				log.setOperateResult("2");
			}else {
//				log.setOperateResult("");
			}
			
			// 保存数据库
			logService.save(log);
		} catch (Exception e) {
			// 记录本地异常日志
			logger.error("==环绕通知异常==");
			logger.error("异常信息:{}", e);
		}
		return rvt;

	}

	/**
	 * 异常通知 用于拦截service层记录异常日志
	 * 
	 * @param joinPoint
	 * @param e
	 */
	@AfterThrowing(pointcut = "serviceAspect()", throwing = "e")
	public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
		Class<?> cl = joinPoint.getTarget().getClass();
		String className = cl.getName();
		String methodName = joinPoint.getSignature().getName();
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest();
		HttpSession session = request.getSession();
		
		// 读取session中的用户
		UserItem currentUser = SessionContextUtil.getCurrentUser();
		// 获取请求ip
		String ip = request.getRemoteAddr();
		// 获取用户请求方法的参数并序列化为JSON格式字符串
		String params = "";
		if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
			for (int i = 0; i < joinPoint.getArgs().length; i++) {
				params += JsonUtil.getJsonStr(joinPoint.getArgs()[i]) + ";";
			}
		}
		try {
			/* ========控制台输出========= */
			System.out.println("=====异常通知开始=====");
			System.out.println("异常代码:" + e.getClass().getName());
			System.out.println("异常信息:" + e.getMessage());
			System.out.println("异常方法:"
					+ (joinPoint.getTarget().getClass().getName() + "."
							+ joinPoint.getSignature().getName() + "()"));
			System.out.println("方法描述:" + getServiceMthodDescription(joinPoint));
			// System.out.println("请求人:" + currentUser.getLoginName());
			System.out.println("请求IP:" + ip);
			System.out.println("请求参数:" + params);
			/* ==========数据库日志========= */
			Log log = new Log();
			log.setOperateComment(getControllerMethodDescription(joinPoint));
			log.setMethod(className + "." + methodName + "()");
			// log.setType("0");
			// log.setExceptionCode(null);
			// log.setExceptionDetail(null);
			// log.setParams(null);
			// log.setCreateBy(user);
			log.setIp(RequestUtil.getClientIp(request));
			if (currentUser == null) {
				log.setOperator(request.getRemoteUser());
			} else {
				log.setOperator(currentUser.getLoginName());
			}
			log.setOperateTime(new Date());
			// 保存数据库
			logService.save(log);
			System.out.println("=====异常通知结束=====");
		} catch (Exception ex) {
			// 记录本地异常日志
			logger.error("==异常通知异常==");
			logger.error("异常信息:{}", ex);
		}
		/* ==========记录本地异常日志========== */
		logger.error("异常方法:{}异常代码:{}异常信息:{}参数:{}", joinPoint.getTarget()
				.getClass().getName()
				+ joinPoint.getSignature().getName(), e.getClass().getName(),
				e.getMessage(), params);

	}

	/**
	 * 获取注解中对方法的描述信息 用于service层注解
	 * 
	 * @param joinPoint
	 *            切点
	 * @return 方法描述
	 * @throws Exception
	 */
	public static String getServiceMthodDescription(JoinPoint joinPoint)
			throws Exception {
		String targetName = joinPoint.getTarget().getClass().getName();
		String methodName = joinPoint.getSignature().getName();
		Object[] arguments = joinPoint.getArgs();
		Class targetClass = Class.forName(targetName);
		Method[] methods = targetClass.getMethods();
		String description = "";
		for (Method method : methods) {
			if (method.getName().equals(methodName)) {
				Class[] clazzs = method.getParameterTypes();
				if (clazzs.length == arguments.length) {
					description = method.getAnnotation(SystemServiceLog.class)
							.description();
					break;
				}
			}
		}
		return description;
	}

	/**
	 * 获取注解中对方法的描述信息 用于Controller层注解
	 * 
	 * @param joinPoint
	 *            切点
	 * @return 方法描述
	 * @throws Exception
	 */
	public static String getControllerMethodDescription(JoinPoint joinPoint)
			throws Exception {
		String targetName = joinPoint.getTarget().getClass().getName();
		String methodName = joinPoint.getSignature().getName();
		Object[] arguments = joinPoint.getArgs();
		Class targetClass = Class.forName(targetName);
		Method[] methods = targetClass.getMethods();
		String description = "";
		for (Method method : methods) {
			if (method.getName().equals(methodName)) {
				Class[] clazzs = method.getParameterTypes();
				if (clazzs.length == arguments.length) {
					description = method.getAnnotation(
							SystemControllerLog.class).description();
					break;
				}
			}
		}
		return description;
	}

}